package com.easonji.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @ClassName: HttpUtils
 * @Description: Http请求工具类
 * @Author: LiuJun
 * @date: 2018/07/07 21:51
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
public class HttpUtils {

    /**
     * 请求编码格式
     */
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 获取HttpServletRequest
     * 
     * @return request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    /**
     * 获取HttpServletResponse
     * 
     * @return response
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        return response;
    }

    /**
     * 获取IP地址
     * 
     * @return IP地址
     */
    public static String getIp() {
        return HttpUtils.getRequest().getRemoteHost();
    }

    /**
     * 获取请求参数
     */
    public static Map<String, String> getRequestParameters() {
        HashMap<String, String> values = new HashMap<>(8);
        HttpServletRequest request = getRequest();
        Enumeration<String> enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String paramName = enums.nextElement();
            String paramValue = request.getParameter(paramName);
            values.put(paramName, paramValue);
        }
        return values;
    }

    /**
     * 发送post请求
     * 
     * @param url
     *            请求地址
     * @param header
     *            请求头信息
     * @param param
     *            请求参数
     * @return 请求结果
     */
    public static String sendPost(String url, Map<String, String> header, String param) {
        String result = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置header信息
        // httpPost.setHeader("Content-type",
        // MediaType.APPLICATION_JSON_UTF8_VALUE);
        if (StringUtils.isNotEmpty(header)) {
            header.forEach((k, v) -> {
                httpPost.setHeader(k, v);
            });
        }
        // 构建消息实体
        StringEntity stringEntity = new StringEntity(param, Charset.forName(CHARSET_UTF8));
        stringEntity.setContentEncoding(CHARSET_UTF8);
        // 发送Json格式的数据请求
        stringEntity.setContentType(MediaType.APPLICATION_JSON_VALUE);
        CloseableHttpResponse response = null;
        // 设置参数到请求对象中
        try {
            httpPost.setEntity(stringEntity);
            // 执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (StringUtils.isNotEmpty(entity)) {
                // 按指定编码转换结果实体为String类型
                result = EntityUtils.toString(entity, CHARSET_UTF8);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            System.out.println("设置请求参数异常");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            System.out.println("执行请求操作异常");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("执行请求操作异常");
            e.printStackTrace();
        } finally {
            if (StringUtils.isNotEmpty(response)) {
                try {
                    // 释放链接
                    response.close();
                } catch (IOException e) {
                    System.out.println("释放链接异常");
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 发送post请求
     * 
     * @param url
     *            请求地址
     * @param header
     *            请求头信息
     * @param param
     *            请求参数
     * @return 请求结果
     */
    public static String sendPost(String url, Map<String, String> header, Map<String, String> param) {
        String result = "";
        // 创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        // 设置header信息
        httpPost.setHeader("Content-type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        if (StringUtils.isNotEmpty(header)) {
            header.forEach((k, v) -> {
                httpPost.setHeader(k, v);
            });
        }
        // 设置请求参数
        List<NameValuePair> nvps = new ArrayList<>();
        if (StringUtils.isNotEmpty(param)) {
            param.forEach((k, v) -> {
                nvps.add(new BasicNameValuePair(k, v));
            });
        }
        CloseableHttpResponse response = null;
        // 设置参数到请求对象中
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, CHARSET_UTF8));
            // 执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (StringUtils.isNotEmpty(entity)) {
                // 按指定编码转换结果实体为String类型
                result = EntityUtils.toString(entity, CHARSET_UTF8);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            System.out.println("设置请求参数异常");
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            System.out.println("执行请求操作异常");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("执行请求操作异常");
            e.printStackTrace();
        } finally {
            if (StringUtils.isNotEmpty(response)) {
                try {
                    // 释放链接
                    response.close();
                } catch (IOException e) {
                    System.out.println("释放链接异常");
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
